package com.passion.common.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;

/**
 * 类描述：http请求发送工具类
 *
 * @author ZhuYin
 * @since 2025年01月02日
 */
@Slf4j
public class HttpRequestUtil {

    private static final CloseableHttpClient HTTP_CLIENT;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100);
        cm.setDefaultMaxPerRoute(50);
        HTTP_CLIENT = HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * 方法说明：发送 application/json 的POST请求
     *
     * @param url         请求地址
     * @param headers     请求头
     * @param params      请求参数
     * @param returnClass 返回对象
     * @return {@link T }
     */
    public static <T>T sendPost(String url, Map<String, String> headers, Map<String, Object> params, Class<T> returnClass) {
        String result = senPostGetResult(url, headers, params);
        return JSON.parseObject(result, returnClass);
    }

    public static String senPostGetResult(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(300000).setConnectionRequestTimeout(300000).setSocketTimeout(300000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-type", "application/json;charset=utf-8");
            httpPost.setHeader("Accept", "application/json");

            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            if (params != null && !params.isEmpty()) {
                httpPost.setEntity(new StringEntity(JSON.toJSONString(params), StandardCharsets.UTF_8));
            }
            String requestId = UUID.randomUUID().toString();
            log.info("application/json POST requestId:{} 请求地址：{}, 请求头：{}, 请求参数：{}", requestId, url, headers == null ? null : JSON.toJSONString(headers), params == null ? null : JSON.toJSONString(params));
            response = HTTP_CLIENT.execute(httpPost);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line;
            String nL = System.lineSeparator();
            while ((line = in.readLine()) != null) {
                sb.append(line).append(nL);
            }
            in.close();
            result = sb.toString();
            log.info("application/json POST requestId:{} 请求结果：{}", requestId, result);
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.error("发送post请求异常：", e);
            }
            log.error("send POST request error: url={}, headers={}, params={}", url, headers, params);
        } finally {
            IOUtils.closeQuietly(response, in);
        }
        return result;
    }

    /**
     * 方法说明：xml请求
     *
     * @param url     url
     * @param headers 请求头
     * @param xml     xml参数
     * @return {@link String }
     * @throws Exception 异常
     */
    public static String postXmlRequest(String url, Map<String, String> headers, String xml) throws Exception {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "text/xml");
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        post.setEntity(new StringEntity(xml, StandardCharsets.UTF_8));

        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(post);

        try {
            return response.getStatusLine().getStatusCode() == 200 ? EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8) : null;
        } finally {
            IOUtils.closeQuietly(client);
        }
    }


}
